const {Router} = require('express')
const router = new Router()

// 引入轮播图模型
const RotationModel = require('../../../model/rotation')

// 引入验证token函数
const {verifyToken} = require('../../../utils/verification')
// 验证权限
const rolesPermission = require('../../../utils/validateRole/rolesPermission')

const path = require('path')
// 移动图片
const moveFile = require('../../../utils/fileUtils/moveFile')
// 删除图片
const removeFile = require('../../../utils/fileUtils/removeFile')
// 格式化时间
const momentTimeX = require('../../../utils/formatTime/momentTime')
// 引入url
const url = require('../../../config/url')

router.post('/bidRotation', function (request, response) {
    const { bidderId, handlerId, goodsId, rotationPic, bidPrice, bidNum, launchStartTime, launchEndTime, isShow } = request.body

    const data = {
        code: '200',
        data: 'error',
        msg: '投标人权限不足'
    }

    // 只有拥有以下角色身份的人才可以进行投标直通车
    const validate = {
        permitRoles: ['admin', 'boss', 'manager'],
        secret: request.get('permission')
    }
    if (!rolesPermission(validate)) return response.json(data)

    const fileName = (path.parse(rotationPic)).base
    const oldPath = path.resolve(__dirname, '../../../public/free/temp/', fileName)
    const newPath = path.resolve(__dirname, '../../../public/charging/rotation', fileName)
    moveFile(newPath, oldPath, status =>{
        data.msg = '投标失败'
        if (!status.isSuccess) return response.json(data);

        let chargeNum = bidNum

        RotationModel.create({
            bidderId,
            handlerId,
            goodsId,
            rotationPic: `${url}public/charging/rotation/${fileName}`,
            bidPrice,
            bidNum,
            chargeNum,
            launchStartTime,
            launchEndTime,
            launchStartTimeX: momentTimeX(launchStartTime),
            launchEndTimeX: momentTimeX(launchEndTime),
            isShow
        },(err, doc)=>{
            if (err) return response.json(data);

            data.data = 'success'
            data.msg = '投标成功'

            return response.json(data)
        })
    })
})

router.post('/updateRotation',function (request, response) {
    let { rotationId, goodsId, bidderId, updateType, oprate} = request.body

    const data = {
        code: '200',
        data: 'error',
        msg: '修改失败'
    }

    RotationModel.findOne({
        goodsId,
        bidderId,
        _id: rotationId
    },function (err, doc) {
        if(err) return response.json(data);

        data.msg = '用户权限不足'
        /*updateType 表示修改直通车的方式
        * 0：表示admin角色才能使用的审核通过或者退回
        * 1：表示经理，老板，职员们的停止直通车计费操作
        * 2：表示经理，老板，职员们的重新编辑直通车
        * */
        updateType = parseInt(updateType)

        // 只有拥有以下角色身份的人才可以进行投标直通车
        const validate = {
            permitRoles: ['admin'],
            secret: request.get('permission')
        }

        const findData = {
            goodsId,
            bidderId,
            _id: rotationId
        }

        if ( updateType == 0 ){
            // 只有拥有以下角色身份的人才可以进行审核
            if (!rolesPermission(validate)) return response.json(data)

            const option = {
                isShow: oprate.isShow
            }
            opreation(findData,option,response)
        }else if(updateType == 1){
            // 只有拥有以下角色身份的人才可以进行停止直通车
            validate.permitRoles = ['admin', 'boss', 'manager']
            if (!rolesPermission(validate)) return response.json(data)

            const option = {
                isShow: oprate.isShow,
                handlerId: request.body.handlerId
            }

            opreation(findData,option,response)
        }else if (updateType == 2){
            // 只有拥有以下角色身份的人才可以编辑直通车
            validate.permitRoles = ['admin', 'boss', 'manager','server']
            if (!rolesPermission(validate)) return response.json(data)

            const { bidPrice, bidNum, chargeNum, launchStartTime, launchEndTime, isShow, rotationPic} = oprate
            const option = {
                bidPrice,
                chargeNum,
                launchStartTime,
                launchEndTime,
                launchStartTimeX: momentTimeX('13:58'),
                launchEndTimeX: momentTimeX(launchEndTime),
                isShow,
                rotationPic,
                handlerId: request.body.handlerId,
                $inc:{
                    bidNum: +bidNum
                }
            }

            // 最难的是编辑因为涉及了图片搬运与删除,且当前照片并未更换时
            if (doc.rotationPic != oprate.rotationPic){
                const fileName = (path.parse(oprate.rotationPic)).base
                const oldPath = path.resolve(__dirname, '../../../public/free/temp/', fileName)
                const newPath = path.resolve(__dirname, '../../../public/charging/rotation', fileName)

                const data2 = {
                    code: '200',
                    data: 'error',
                    msg: '修改失败'
                }

                moveFile(newPath, oldPath, status=>{
                    if (!status.isSuccess) return response.json(data2);

                    const oldFileName = (path.parse(doc.rotationPic)).base

                    removeFile(
                        path.resolve(__dirname, '../../../public/charging/rotation', oldFileName), status1=>{
                        if (!status1.isSuccess) return response.json(data2);

                        option.rotationPic = `${url}public/charging/rotation/${fileName}`

                        opreation(findData,option,response)
                    })
                })
            }else {
                opreation(findData,option, response)
            }
        }else {
            data.msg = '更新类型不合法'
            return response.json(data)
        }
    })
})

function opreation(findData,option, response){
    const data1 = {
        code: '200',
        data: 'error',
        msg: '修改失败'
    }

    RotationModel.findOneAndUpdate(findData,option,function (err,doc) {
        if (err) return response.json(data1);

        data1.data = 'success'
        data1.msg = '修改成功'
        return response.json(data1)
    })
}


module.exports = router
